//
//  EditImageTextViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/9.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "EditImageTextViewController.h"
//#import "TWPhotoPickerController.h"
#import "imageVPickController.h"
@interface EditImageTextViewController ()<UITableViewDelegate, UITableViewDataSource,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate>
{
    CGPoint TouchPosition;
}
@property (strong, nonatomic) UITableView *imageTableView;
@property (strong, nonatomic) UITableView *textTableView;
@property (strong, nonatomic) NSMutableArray *image;
@property (strong, nonatomic) NSMutableArray *text;
@end

@implementation EditImageTextViewController
- (void)getImageArray:(NSArray *)iamge textArray:(NSArray *)text
{
    self.image = [[NSMutableArray alloc] initWithArray:iamge];
    self.text = [[NSMutableArray alloc] initWithArray:text];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [backBtn setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backToEdit:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *doneBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [doneBtn setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [doneBtn addTarget:self action:@selector(doneToEdit:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    UIBarButtonItem *doneBtnItem = [[UIBarButtonItem alloc] initWithCustomView:doneBtn];
    self.navigationItem.leftBarButtonItem = backBtnItem;
    self.navigationItem.rightBarButtonItem = doneBtnItem;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 0.525, 30)];
    
    UILabel *imageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.frame.size.width / 2, titleView.frame.size.height)];
    imageLabel.text = @"图";
    imageLabel.textColor = [UIColor blackColor];
    imageLabel.textAlignment = NSTextAlignmentLeft;
    [titleView addSubview:imageLabel];
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleView.frame.size.width / 2, 0, titleView.frame.size.width / 2, titleView.frame.size.height)];
    textLabel.text = @"文";
    textLabel.textColor = [UIColor blackColor];
    textLabel.textAlignment = NSTextAlignmentRight;
    [titleView addSubview:textLabel];
    self.navigationItem.titleView = titleView;
    [self createTableView];
    // Do any additional setup after loading the view.
}
- (void)backToEdit:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)doneToEdit:(UIButton *)sender
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    for (int i = 0; i < _text.count; i++) {
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
//        TextTableViewCell *result = (TextTableViewCell *)[_textTableView cellForRowAtIndexPath:indexpath];
//        NSString *time = [_text[indexpath.row] valueForKey:@"timeline"];
//        NSString *content = [_text valueForKey:@"content"];
        NSDictionary *dic = _text[i];//[NSDictionary dictionaryWithObjectsAndKeys:content, @"content", time, @"timeline", nil];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:dic,@"newText",[NSNumber numberWithInt:i], @"index", nil];
//        NSLog(@"%@----%@, %@", dict, result, indexpath);
        [_text replaceObjectAtIndex:indexpath.row withObject:dict];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"replaceText" object:dict];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)createTableView
{
    self.imageTableView = [[UITableView alloc] initWithFrame:CGRectMake(15, -7, (self.view.frame.size.width - 60) / 2, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _imageTableView.delegate = self;
    _imageTableView.dataSource = self;
    _imageTableView.bounces = NO;
    _imageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _imageTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_imageTableView];
    
    self.textTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, 0, self.view.frame.size.width / 2 - 15, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _textTableView.bounces = NO;
    _textTableView.delegate = self;
    _textTableView.dataSource = self;
    _textTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _textTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_textTableView];
    
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _textTableView) {
        return _text.count;
    } else if (tableView ==  _imageTableView) {
        return _image.count;
    } else {
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _textTableView) {
        return _imageTableView.frame.size.width + 7;
    } else if (tableView ==  _imageTableView) {
        return _imageTableView.frame.size.width + 7;
    } else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _textTableView) {
        static NSString *textTableIdentifier = @"text";
        TextTableViewCell *textCell = [tableView dequeueReusableCellWithIdentifier:textTableIdentifier];
        if (textCell == nil) {
            textCell = [[TextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:textTableIdentifier];
            [textCell.deleteText addTarget:self action:@selector(deleteText:event:) forControlEvents:UIControlEventTouchUpInside];
            textCell.textShow.delegate = self;
        }
//        textCell.backgroundColor = [UIColor redColor];
        textCell.textShow.text = [_text[indexPath.row] valueForKey:@"content"];
        return textCell;
    } else if (tableView == _imageTableView){
        static NSString *imageTableIdentifier = @"image";
        ImageTableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:imageTableIdentifier];
        if (imageCell == nil) {
            imageCell = [[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imageTableIdentifier];
            [imageCell.editImage addTarget:self action:@selector(deleteOrChangeImage:event:) forControlEvents:UIControlEventTouchUpInside];
        }
//        imageCell.backgroundColor = [UIColor blueColor];
        if (indexPath.row == 0) {
            imageCell.imageType.image = [UIImage imageNamed:@"changeCover"];
            imageCell.editImage.hidden = YES;
        } else {
            imageCell.imageType.hidden = YES;
            [imageCell.editImage setImage:[UIImage imageNamed:@"edit_delete_button"] forState:UIControlStateNormal];
        }
        NSDictionary *dic = _image[indexPath.row];
        imageCell.imageShow.image = [dic objectForKey:@"image"];
        return imageCell;
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _imageTableView) {
        if (indexPath.row == 0) {
            imageVPickController *imagePicker = [[imageVPickController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            // [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self getSelectedPhoto:img];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteOrChangeImage:(UIButton *)sender event:(id)event
{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_imageTableView];
    NSIndexPath *indexPath= [_imageTableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath!= nil)
    {
        if (indexPath.row != 0) {
            [_image removeObjectAtIndex:indexPath.row];
            [_imageTableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"editImageText" object:indexPath];
        }
    }
}
- (void)getSelectedPhoto:(UIImage *)photos
{
        NSString *timeline = @"0.000000";
        NSDictionary *imgDic = [NSDictionary dictionaryWithObjectsAndKeys:photos,@"image", timeline, @"timeline", nil];
        [self.image replaceObjectAtIndex:0 withObject:imgDic];
        [_imageTableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeFirstImage" object:photos];
}
- (void)deleteText:(UIButton *)sender event:(id)event
{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_textTableView];
    NSIndexPath *indexPath= [_textTableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath!= nil)
    {
        [_text removeObjectAtIndex:indexPath.row];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteText" object:indexPath];
        [_textTableView reloadData];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.navigationItem.rightBarButtonItem.customView.hidden = YES;
    TextTableViewCell *textcell = (TextTableViewCell *)textView.nextResponder;
    NSIndexPath *cellIndex = [_textTableView indexPathForCell:textcell];

    if (cellIndex.row > 1) {
        [_textTableView setContentOffset:CGPointMake(0, textcell.frame.origin.y) animated:YES];
    }
}
- (void)textViewDidChange:(UITextView *)textView
{
//    [textView.text enumerateSubstringsInRange:NSMakeRange(0, [textView.text length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
//        const unichar hs = [substring characterAtIndex:0];
//        if (0xd800 <= hs && hs <= 0xdbff) {
//            if (substring.length > 1) {
//                const unichar ls = [substring characterAtIndex:1];
//                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
//                if (0x1d000 <= uc && uc <= 0x1f77f) {
//                    [textView deleteBackward];
//                }
//            }
//        } else if (substring.length > 1) {
//            const unichar ls = [substring characterAtIndex:1];
//            if (ls == 0x20e3) {
//                [textView deleteBackward];
//            }
//        } else {
//            if (0x2100 <= hs && hs <= 0x27ff) {
//                [textView deleteBackward];
//            } else if (0x2B05 <= hs && hs <= 0x2b07) {
//                [textView deleteBackward];
//            } else if (0x2934 <= hs && hs <= 0x2935) {
//                [textView deleteBackward];
//            } else if (0x3297 <= hs && hs <= 0x3299) {
//                [textView deleteBackward];
//            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
//                [textView deleteBackward];
//            }
//        }
//    }];
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    TextTableViewCell *cell = (TextTableViewCell *)textView.nextResponder;
    NSIndexPath *indexPath = [_textTableView indexPathForCell:cell];
    NSString *time = [_text[indexPath.row] valueForKey:@"timeline"];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:textView.text,@"content", time, @"timeline", nil];
    [_text replaceObjectAtIndex:indexPath.row withObject:dic];
    [_textTableView reloadData];
    return YES;
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    [_textTableView setContentOffset:CGPointZero animated:YES];
    self.navigationItem.rightBarButtonItem.customView.hidden = NO;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location>=40)
    {
        //控制输入文本的长度
        return  NO;
    } else {
        if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
            return YES;
        }
    }
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        TextTableViewCell *result = (TextTableViewCell *)textView.superview;
        NSIndexPath *indexPath= [_textTableView indexPathForCell:result];
        NSString *time = [_text[indexPath.row] valueForKey:@"timeline"];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:textView.text,@"content", time, @"timeline", nil];
        [_text replaceObjectAtIndex:indexPath.row withObject:dic];
//        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:dic,@"newText",indexPath, @"index", nil];
        [_textTableView reloadData];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"replaceText" object:dict];
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
